#include "Protocol.hpp"
#include "TcpServer.hpp"
#include "Socket.hpp"
#include "Calculate.hpp"

#include <string>
#include <memory>
#include <cstring>

#include <unistd.h>

using namespace Net_Work;
using namespace Protocol;

std::string HandlerRequest(std::string &inbufferstream, bool *error_code)
{
    *error_code = true;
    // 计算机对象
    Calculate calculate;
    // 构建响应对象
    std::unique_ptr<Factory> factory(new Factory());
    auto req = factory->BuildRequest();

    // 分析字节流, 是否存在完整报文
    std::string total_resp_string;
    std::string message;
    while (Decode(inbufferstream, &message))
    {
        std::cout << message << " ------ message" << std::endl;

        // 一定存在完整报文，反序列化
        if (!req->Deserialize(message))
        {
            std::cout << "Deserialize error" << std::endl;
            *error_code = false;
            return std::string();
        }
        std::cout << "Deserialize success" << std::endl;
        // 处理业务
        auto resp = calculate.Cal(req);
        // 序列化resp
        std::string send_string;
        resp->Serialize(&send_string);
        // 构建字符串级别的相应报文
        send_string = Encode(send_string);
        // 发送
        total_resp_string += send_string;
    }
    return total_resp_string;
}

// ./server port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        cout << "Usage: " << argv[0] << " port" << endl;
        return 0;
    }
    uint16_t localport = std::stoi(argv[1]);
    std::unique_ptr<Tcp_Server> svr(new Tcp_Server(localport, HandlerRequest));

    svr->Loop();

    return 0;
}
